<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="老人姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.serve_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工电话" prop="userPhonenumber">
        <el-input
          v-model="queryParams.userPhonenumber"
          placeholder="请输入员工电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="街道" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择所在街道" clearable>
          <el-option
            v-for="item in deptList"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="开始时间" prop="beginTime" label-width="120">
        <el-date-picker clearable
          v-model="queryParams.beginTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择任务起始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="截止时间" prop="endTime" label-width="120">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择任务截止时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['serve:serveTask:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['serve:serveTask:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['serve:serveTask:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['serve:serveTask:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serveTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工姓名" align="center" prop="userName" />
      <el-table-column label="老人姓名" align="center" prop="customerName" />
      <el-table-column label="老人照片" align="center" prop="customerImg" width="120">
        <template slot-scope="scope">
          <el-image style="width:50px; height: 50px" :src="scope.row.customerImg" :preview-src-list="[scope.row.customerImg]"/>
        </template>
      </el-table-column>
      <el-table-column label="任务起始时间" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务截止时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.serve_task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleTaskItem(scope.row)"
            v-hasPermi="['serve:serveTask:edit']"
          >服务记录</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['serve:serveTask:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['serve:serveTask:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工" prop="userName">
          <pagination-select  v-model="form.userName"  :dataList="userList"
            :label-key="'nickName'" :value-key="'userId'" :page-info="userPageInfo"  @selectChange="selectUser"></pagination-select>
        </el-form-item>
        <el-form-item label="老人" prop="customerName">
          <pagination-select  v-model="form.customerName"  :dataList="customerList"
                              :label-key="'customerName'" :value-key="'id'" :page-info="customerPageInfo"  @selectChange="selectCustomer"></pagination-select>
        </el-form-item>
        <el-form-item label="服务项目" prop="serviceItemIds" label-width="120">
          <el-checkbox-group v-model="form.serviceItemIds">
            <el-checkbox v-for="(item,index) in serviceItemList" :key="index" :label="item.id" >{{item.itemName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="任务起始时间" prop="beginTime" label-width="120">
          <el-date-picker clearable
            v-model="form.beginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择任务起始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务截止时间" prop="endTime" label-width="120">
          <el-date-picker clearable
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择任务截止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.serve_task_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listServeTask, getServeTask, delServeTask, addServeTask, updateServeTask } from "@/api/serve/serveTask";
import { listUser } from "@/api/system/user";
import {listServiceItem} from "@/api/base/serviceItem";
import PaginationSelect from "@/components/PaginationSelect";
import {listCustomer} from "@/api/base/customer";
import {listDept} from "@/api/system/dept";
export default {
  name: "ServeTask",
  components: {PaginationSelect},
  dicts: ['serve_task_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务任务表格数据
      serveTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userPhonenumber: undefined,
        beginTime: undefined,
        endTime: undefined,
        status: undefined,
        userType:'app_user'
      },
      // 表单参数
      form: {
        userId:undefined,
        userName:undefined,
        customerId:undefined,
        customerName: undefined,
        serviceItemIds:[]
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "服务人员不能为空" }
        ],
        customerName: [
          { required: true, message: "老人不能为空"}
        ],
        beginTime: [
          { required: true, message: "任务起始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "任务截止时间不能为空", trigger: "blur" }
        ],
        serviceItemIds: [
          { required: true, message: "请勾选服务项目", trigger: "blur" }
        ],
      },
      userList:[],
      userPageInfo:{
        pageNum: 1,
        pageSize: 10,
        total:10
      },
      customerList:[],
      customerPageInfo:{
        pageNum: 1,
        pageSize: 10,
        total:10
      },
      serviceItemList:[],
      //街道
      deptList:[],

    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getCustomerList();
    this.getServiceItemList();
    //查询街道
    this.getDeptList();
  },
  methods: {
    //获取服务项目
    getServiceItemList(){
      this.loading = true;
      listServiceItem().then(response => {
        this.serviceItemList = response.data;
        this.loading = false;
      });
    },
    /** 查询街道 */
    getDeptList() {
      this.loading = true;
      listDept({parentId:100}).then(response => {
        this.deptList = response.data;

        //选中查询条件中的部门
        if(this.deptId){
          this.queryParams.deptId = parseInt(this.deptId) ;
        }
        this.loading = false;
        //查询服务记录
        this.getList();
      });
    },
    //选择用户
    selectUser(value){
      this.form.userId = value.substring(0,value.indexOf('-'));
      // this.form.userName = value.substring(value.indexOf('-')+1);

      this.$set(this.form,'userName',value.substring(value.indexOf('-')+1))

      console.log(this.form.userName)
      //查询他服务的老人
      this.getCustomerList(this.form.userId);
    },
    /**查询老人*/
    getCustomerList(userId){
      this.loading = true;
      this.customerList = [];
      listCustomer({'userId':userId}).then(response => {
        this.customerList = response.rows;
        this.customerPageInfo.total = response.total;
        this.loading = false;
      });
    },
    //选择老人
    selectCustomer(value){
      // this.form.customerName = value.substring(value.indexOf('-')+1);
      this.form.customerId = value.substring(0,value.indexOf('-'));
      this.$set(this.form,'customerName',value.substring(value.indexOf('-')+1))
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser({'userType':'app_user'}).then(response => {
          this.userList = response.rows;
          this.userPageInfo.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询服务任务列表 */
    getList() {
      this.loading = true;
      listServeTask(this.queryParams).then(response => {
        this.serveTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        customerId: undefined,
        beginTime: undefined,
        endTime: undefined,
        status: "0",
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        updateBy: undefined,
        serviceItemIds:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getServeTask(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改服务任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateServeTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addServeTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除服务任务编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delServeTask(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('serve/serveTask/export', {
        ...this.queryParams
      }, `serveTask_${new Date().getTime()}.xlsx`)
    },
    /** 查看任务服务项目 */
    handleTaskItem(row) {
      this.$router.push({ path: '/serve/serveTaskItem/index?taskId=' + row.id})
    },
  }
};
</script>
